$(function () {
    // 获取枚举类
    $.get(baseURL + "storeMaterials/storematerialin/getEnum", function(r){
        vm.e.whetherEnum = r.whetherEnum;
        vm.e.stockMaterialIoTypeEnum = r.stockMaterialIoTypeEnum;
        vm.e.directionEnum = r.directionEnum;
        vm.e.storeMaterialInStatusEnum = r.storeMaterialInStatusEnum;
        vm.e.financePaymentStatusEnum = r.financePaymentStatusEnum;


		// 获取采购供应商信息
		$.get(baseURL + "purchase/storepurchaseapply/getEnumList/", function(r){
			vm.e.materialSupplier = r.materialSupplier;
			// console.log( vm.e.materialSupplier);
		});

    });
    // 获取耗材分类树信息
    $.get(baseURL + "material/materialcategory/getTree/", function(r){
        if(r.code == 0){
            vm.materialCategoryList = r.result.materialCategoryTree;
            // vm.e.materialUnitEnum = r.materialUnitEnum;
            // vm.e.materialSupplier = r.materialSupplier;
            // vm.e.purchaseApplyStatusEnum = r.purchaseApplyStatusEnum;
            // vm.e.selectMDList = r.getSelectMD;
            // console.log( vm.e.materialSupplier);
        }else{
            alert(r.msg);
        }
    });

    $("#jqGrid").jqGrid({
        url: baseURL + 'storeMaterials/storematerialin/list',
        datatype: "json",
        colModel: [
            { label: '操作', name: 'inId' , align: 'center', width: 80,
                formatter:function(value, options, row){
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="vm.auditOrRejectData={id:'+row.inId+',operate:1,msg:\'确认审核通过？\'}; vm.auditDialogVisible = true">审核</a>') ;
                    actions.push('|') ;
                    actions.push('<a href="javascript:void(0);" onclick="vm.auditOrRejectData={id:'+row.inId+',operate:0,msg:\'确认驳回？\'}; vm.auditDialogVisible = true">驳回</a>') ;
                    actions.push('|') ;
                    actions.push('<a href="javascript:void(0);" onclick="vm.detailShow(' + row.inId + ');">查看</a>');
                    return actions.join('  ');
                }
            },
			{ label: '入库ID', name: 'inId', index: 'in_id', width: 50, key: true ,align:'center'},
			{ label: '单据号', name: 'inNo', index: 'in_no', width: 80 ,align:'center' },
			{ label: '总金额', name: 'totalMoney', index: 'total_money', width: 80, align:'right'},
			{ label: '是否含税', name: 'tax', width: 80, align:'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    $.each(vm.e.whetherEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
            },
			{ label: '库存交易类型', name: 'type', index: 'type', width: 80, align:'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    $.each(vm.e.stockMaterialIoTypeEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
            },
			{ label: '库存交易方向', name: 'direction', index: 'direction', width: 80, align:'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    $.each(vm.e.directionEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
             },
			{ label: '单据状态', name: 'status', index: 'status', width: 60, align:'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    $.each(vm.e.storeMaterialInStatusEnum, function (index, module) {
                        if (module.id == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
             },
            { label: '入库单据', name: 'purchaseImages', index: 'purchaseImages', width: 40, align:'center',
                formatter:function(value,options,row){
                    if(row.status == 2){
                        //已入库的可以上传查看单据
                        return '<a onclick="viewReceipts(\''+ value +'\','+ row.inId +')">查看</a>';
                    }else{
                        //未入库的可以无
                        return '<p>-</p>';
                    }
                }
            },
			{ label: '备注', name: 'remark', index: 'remark', width: 80},
			{ label: '创建人', name: 'createName', index: 'create_name', width: 80, align:'center'},
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 80, align:'center'},
			{ label: '审核人', name: 'checkName', index: 'check_name', width: 80, align:'center'},
			{ label: '审核时间', name: 'checkTime', index: 'check_time', width: 80, align:'center'},
			/*{ label: '财务状态', name: 'paymentStatus', index: 'payment_status', width: 80, align:'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    $.each(vm.e.financePaymentStatusEnum, function (index, module) {
                        if (module.value == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }
            },*/
			// { label: '详情', name: 'detail', index: 'detail', align:'center' , width:80,
			// 	formatter:function (value,option,row) {
			// 		var actions = [];
			// 		actions.push('<a href="javascript:void(0);" onclick="vm.detailShow(' + row.inId + ');">查看</a>');
			// 		return actions.join(' ');
			// 	}
			// },
        ],
		viewrecords: true,
        height: 600,
        rowNum: 20,
		rowList : [25,50,100],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

function viewReceipts(value,inId){
    vm.viewReceipts(value,inId);
}

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		showDetail: true,
        showListFalse:false,
        profitDiv:false,
        auditDialogVisible:false,   //  审核弹框
		e: {
            storeMaterialInTypeList: [
            	{value: '1',label: '采购入库'},
				{value: '7',label: '调拨入库'},
                {value: '2',label: '红冲'}

            ],
			materialSupplier: [],
            taxTypeList: [
                {value: 1,label: '含税'},
                {value: 0,label: '不含税'},
            ],
            materialUnitEnum : [
                {id: 0,describe: '个'},
                {id: 1,describe: 'm²'},
                {id: 2,describe: 'g'},
                {id: 3,describe: 'm'},
                {id: 4,describe: '张'},
			],
            whetherEnum:[],
            stockMaterialIoTypeEnum:[],
            directionEnum:[],
            storeMaterialInStatusEnum:[],
            financePaymentStatusEnum:[],
            taxEnum:[{value: 1,label: '含税'},{value: 0,label: '不含税'}],
		},
        q: {
            inNo:null
        },
		storeMaterialForm: {
            storeMaterialInEntity: {},
            storeMaterialInDetailEntityList: []
		},
        auditOrRejectData: {
		    id:null,
            operate:null,
            msg:"提示",
        },
        //-------------------------------------盘盈新增--------------------------------------------------------------
        materialCategorySearch:null,
        materialCategoryList:[],
        defaultProps: {
            children: 'children',
            label: 'label'
        },
        materialTableData: [],
        purchaseApplyForm: {
            storePurchaseApplyEntity:{
                totalMoney: 0.00,
                tax: null,
                applyRemark:null,
                auditRemark:null
            },
            storePurchaseApplyDetailEntityList: []
        },
        materialSearchForm: {
            materialName: null
        },
        page:{
            current:1, // 当前页
            size:20, // 分页数
            total:0, // 总条数
        },
        addMaterialList: [], // 已添加耗材ID集合
        //---------入库单据
        otherAccessoryList:[],
        otherAccessoryDialog:false,
        //点击弹框的入库id
        dialogInNo:null,
	},
    watch: {
        materialCategorySearch(val) {
            this.$refs.tree2.filter(val);
        }
    },
    mounted: function () {
        /* oss上传 */
        $.files_up_oss({
            id: ["upload"],//按钮id
            url: "/sys/oss/getSignature",
            dir: "sotre/materialin/images/",
            file_type: "jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z",
            size: "100mb",//mb
            view_url: "https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/"
        }, function (index_number, json) {
            if (json.Status == 'OK') {
                //处理
                var otherAccessory = {};
                otherAccessory.name = json.oldFilename;
                otherAccessory.imageUrl = json.filename;
                otherAccessory.type = 3;
                otherAccessory.size = json.size;
                otherAccessory.fileType = json.mimeType;
                $.ajax({
                    type: "POST",
                    url: baseURL + "otherAccessory/otheraccessory/storeMaterialSave",
                    contentType: "application/json",
                    data: JSON.stringify(otherAccessory),
                    success: function(r){
                        if(r.code == 0){
                            vm.otherAccessoryList.push(r.otherAccessory);
                        }else{
                            alert(r.msg)
                        }
                    }
                })
            }
        })
    },
    updated: function(){
	    if (this.otherAccessoryList.length >0){
            $('#view').viewer('destroy');
            $('#view').viewer();
        }
    },
	methods: {
		query: function () {
			vm.reload();
		},
        reset: function(){
            vm.q = {
                inNo:null
            }
            vm.reload();
        },
        addIn: function(){
			vm.showList = false;
			vm.showListFalse = true;
			vm.storeMaterialForm = {
                storeMaterialInEntity: {
                    type:null,
                    inNo:null,
                    tax:0,
                    applyRemark:null,
                    auditRemark:null
				},
                storeMaterialInDetailEntityList: []
			};
		},

		// 获取已经详细信息
		// 获取明细
		getInfo: function (inId) {
			$.get(baseURL + "storeMaterials/storematerialin/info/" + inId, function (r) {
				vm.purchaseApplyForm.storePurchaseApplyEntity = r.infoData;
				vm.purchaseApplyForm.storePurchaseApplyEntity.stockName = r.stockName;
			});

			$.get(baseURL + "storeMaterials/storematerialin/storematerialInDetailList/" + inId, function (r) {
				vm.purchaseApplyForm.storePurchaseApplyDetailEntityList = r.liststorematerialIndetail;
			});
		},

		detailShow: function (inId) {
			this.showList = false;
			this.showDetail = false;
			vm.title = "入库详情"
			vm.getInfo(inId);
		},


		close: function (event) {
			vm.showList = true
			vm.showListDetail = false
			vm.showDetail = true
		},




        //盘盈
        profit:function(){
            vm.showList = false;
            vm.profitDiv = true;
            //重置材料table
            vm.materialTableData = [];
        },
        //入库类型改变的时候,重置值
        clearStore:function(){
            vm.storeMaterialForm.storeMaterialInDetailEntityList = [];
            vm.storeMaterialForm.storeMaterialInEntity.applyRemark = null;
            vm.storeMaterialForm.storeMaterialInEntity.auditRemark = null;
            vm.storeMaterialForm.storeMaterialInEntity.outRemark = null;
        },
        save: function (event) {
			$.ajax({
				type: "POST",
			    url: baseURL + "storeMaterials/storematerialin/saveIn",
                contentType: "application/json",
			    data: JSON.stringify(vm.storeMaterialForm),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		reload: function (event) {
			vm.showList = true;
			vm.showListFalse = false;
			vm.profitDiv = false;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:{
                    'inNo': vm.q.inNo,
                },
            }).trigger("reloadGrid");
		},
        searchInNo: function () {
			console.log(vm.storeMaterialForm.storeMaterialInEntity)

			if(vm.storeMaterialForm.storeMaterialInEntity.type == null){
				alert("请选择入库类型！")
			}else if(vm.storeMaterialForm.storeMaterialInEntity.inNo == null){
                alert("请输入单据号！")
			}
            var postData = {
                type: vm.storeMaterialForm.storeMaterialInEntity.type,
				inNo: vm.storeMaterialForm.storeMaterialInEntity.inNo
			};
            $.ajax({
                type: "POST",
                url: baseURL + "storeMaterials/storematerialin/queryInDetial",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function(r){
                    console.log(r)
                    vm.storeMaterialForm.storeMaterialInDetailEntityList = r.materiallist;
                    if(r.remarks != null){
                        debugger;
                        vm.storeMaterialForm.storeMaterialInEntity.applyRemark = r.remarks.applyRemark;
                        vm.storeMaterialForm.storeMaterialInEntity.auditRemark = r.remarks.auditRemark;
                        vm.storeMaterialForm.storeMaterialInEntity.outRemark = r.remarks.outRemark;
                        if(r.remarks.tax){
                            vm.storeMaterialForm.storeMaterialInEntity.tax = 1
                        }else{
                            vm.storeMaterialForm.storeMaterialInEntity.tax = 0
                        }
                        console.info(vm.storeMaterialForm.storeMaterialInEntity.tax);
                    }
                }
            });
        },
		changeInput: function (val,val2) {
				console.log(val);
				console.log(this.val2);
				// alert("入库数量不能大于实际发货数量");

		},
        /*格式化 单位*/
        formatUnit: function (row, column, cellValue, index) {
            for(var i=0; i<this.e.materialUnitEnum.length; i++){
                if(cellValue == this.e.materialUnitEnum[i].id){
                    return this.e.materialUnitEnum[i].describe
                }
            }
        },
        //-----------------------------------------------------------------------------------盘盈新增的方法-----------------------------
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        /*查询耗材*/
        materialsSearch(data) {
            var  paramData = {}
            if(typeof(data.id) == "undefined"){
                paramData.materialName =  this.materialSearchForm.materialName;
            }else{
                paramData.categoryId = data.id;
                this.materialSearchForm.materialName = null;
            }
            var queryData = {page: this.page, params: paramData};
            //ajax 请求
            $.ajax({
                type: "POST",
                url: baseURL + "material/material/queryMaterialsList",
                contentType: "application/json",
                data: JSON.stringify(queryData),
                success: function (r) {
                    if (r.code == 0) {
                        vm.page.size = r.result.page.size;
                        vm.page.total = r.result.page.total;
                        vm.materialTableData = r.result.page.records;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /*分页数改变*/
        handleSizeChange(val) {
            vm.page.size = val;
            this.materialsSearch(val);
        },
        /*分页当前页改变改变*/
        handleCurrentChange(val) {
            this.page.current = val
            this.materialsSearch(val);
        },
        /*添加耗材到采购列表*/
        addMaterial: function (row) {
            if(this.addMaterialList.indexOf(row.materialId)>=0){
                alert("耗材："+row.materialName+" 已添加！")
                return;
            }
            var storePurchaseApplyDetail = {
                materialId:row.materialId,
                materialName:row.materialName,
                specifications:row.specifications,
                length:row.length,
                width:row.width,
                supplierId:row.supplierId,
                unit:row.unit,
                materialQuantity:1,
                totalMoney:0,
                weight:row.weight
            }
            this.purchaseApplyForm.storePurchaseApplyDetailEntityList.push(storePurchaseApplyDetail);
            this.addMaterialList.push(row.materialId);
        },
        /*移除采购列表耗材*/
        removePurchaseMaterials: function (row,index) {
            this.purchaseApplyForm.storePurchaseApplyDetailEntityList.splice(index,1)

            var materialIdIndex = vm.addMaterialList.indexOf(row.materialId);
            vm.addMaterialList.splice(materialIdIndex,1);

            vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = Number(vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney)
                - Number(row.totalMoney)
        },
        /*单个耗材，采购总价修改事件*/
        totalMoneyChange: function (row,index) {
            var storePurchaseApplyDetail = this.purchaseApplyForm.storePurchaseApplyDetailEntityList[index];
            storePurchaseApplyDetail.unitMoney = percentNum(storePurchaseApplyDetail.totalMoney,storePurchaseApplyDetail.materialQuantity)
            this.purchaseApplyForm.storePurchaseApplyDetailEntityList.splice(index,1,storePurchaseApplyDetail);

            // 修改采购总价
            this.changePurchaseTotal();
        },
        // 修改采购总价
        changePurchaseTotal: function () {
            vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = 0
            for(var i=0; i<this.purchaseApplyForm.storePurchaseApplyDetailEntityList.length; i++){
                vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = Number(vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney)
                    + Number(vm.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].totalMoney);
            }
        },
        //盘存提交
        onSubmit: function (event) {
            //
            $.ajax({
                type: "POST",
                url: baseURL + "storeMaterials/storematerialin/save",
                contentType: "application/json",
                data: JSON.stringify(this.purchaseApplyForm),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        //入库单据上传
        viewReceipts:function(value,inId){
            vm.dialogInNo = inId;
            //若value不为空,则请求后台获得图片数据信息
            if(!isBlank(value)){
                $.ajax({
                    type: "POST",
                    url: baseURL + "otherAccessory/otheraccessory/getMerchantReceipts/"+value,
                    contentType: "application/json",
                    success: function(r){
                        if(r.code === 0){
                            vm.otherAccessoryList = r.otherAccessoryList;
                            // setTimeout("vm.viewPicture()",1000);
                            // vm.viewPicture()
                        }else{
                            alert(r.msg);
                        }
                    }
                })
            }
            //打开单据上传图片Dialog
            vm.otherAccessoryDialog = true;
        },
        //保存弹框单据记录的信息
        saveOtherAccessory:function(){
            //vm.otherAccessoryList
            //vm.dialogInNo
            var ids = [];
            for(var i = 0;i<vm.otherAccessoryList.length;i++){
                ids.push(vm.otherAccessoryList[i].id);
            }
            console.info("保存ids:"+ ids.join(",") +"到单据号:"+vm.dialogInNo);
            var str = ids.join(",");
            if(isBlank(str)){
                str = 0;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "storeMaterials/storematerialin/editOtherAccessory/"+vm.dialogInNo+"/"+str,
                contentType: "application/json",
                success: function(r){
                    if(r.code == 0){
                        //保存成功,关闭弹窗
                        vm.otherAccessoryDialog = false;
                    }else{
                        alert(r.msg)
                    }
                }
            })
        },
        //用户点了取消保存
        cancel:function(){
            //提示用户是否放弃此次编辑
            this.$confirm('该操作将放弃对单据号的本次修改, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //关闭
                vm.otherAccessoryDialog = false;
                //重置弹窗内容
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '请继续修改'
                });
            });
        },
        //移除单据
        delOtherAccessory:function(id){
            for(var i = 0;i<vm.otherAccessoryList.length;i++){
                if(vm.otherAccessoryList[i].id == id){
                    vm.otherAccessoryList.splice(i,1);
                }
            }
        },
        //页面关闭重置元素
        reloadDialog:function(){
            vm.otherAccessoryList = [];
            vm.dialogInNo = null;
            vm.reload();
        },
	}
});

/**
 * 审核
 */
function auditOrReject() {
    console.log(vm.auditOrRejectData);
    var url = "storeMaterials/storematerialin/audit/"+vm.auditOrRejectData.id;
    if(vm.auditOrRejectData.operate == 0){
        url = "storeMaterials/storematerialin/reject/"+vm.auditOrRejectData.id;
    }
    $.get(baseURL + url, function(r){
        if(r.code == 0){
            alert(r.msg);
        }else{
            alert(r.msg);
        }
		vm.reload();
    });
    vm.auditDialogVisible = false;
}
function percentNum(num,num2) {
    return (Math.round(num / num2 * 100) / 100.00);
}